const logger = require("../../utils/logger")
const mysqlUtil = require("../../utils/mysqlUtil")
const moment = require('moment')
const redisUtil = require("../../utils/redisUtil")

// 生成一个新的用户id
async function newUid() {

    for (let i = 0; i != 3; i++) {
        let uid = 100001 + Math.floor(899998 * Math.random())
        let res = await mysqlUtil.execute('SELECT 1 FROM tb_user WHERE uid = ? LIMIT 1', [uid])
        if (res.length == 0) return uid
    }

    return 0
}

module.exports = {
    // 员工列表
    userList: async ctx => {
        let args = ctx.query;
        let pageIndex = parseInt(args.pageIndex || 1);
        let pageCount = parseInt(args.pageCount || 10);
        try {
            // 查询有多少条记录
            let res = await mysqlUtil.execute('SELECT COUNT(1) cnt FROM tb_user');
            let count = res[0].cnt;
            // 查询员工信息
            let sql = `
                SELECT
                    tb_user.id,
                    tb_user.uid,
                    tb_user.name,
                    tb_user.gender,
                    tb_user.leixing,
                    tb_user.xingzhi,
                    tb_user.zhiji,
                    tb_user.upper,
                    tb_user.phone,
                    tb_user.email,
                    tb_user.sta,
                    tb_user.password,
                    tb_user.createtime,
                    tb_user_depart_pos.id dpid,
                    tb_user_depart_pos.department,
                    con_department.name departmentName,
                    tb_user_depart_pos.position,
                    con_position.name positionName
                FROM tb_user
                LEFT JOIN tb_user_depart_pos ON tb_user_depart_pos.uid = tb_user.uid
                LEFT JOIN con_department ON tb_user_depart_pos.department = con_department.id
                LEFT JOIN con_position ON tb_user_depart_pos.position = con_position.id
                WHERE 1=1 
            `
            let params = [];
            if (args.name) {
                sql += 'AND tb_user.name = ? ';
                params.push(args.name);
            }
            sql += 'LIMIT ?, ?';
            params.push((pageIndex - 1) * pageCount, pageCount);
            res = await mysqlUtil.execute(sql, params);
            // 根据员工id进行分类，部门岗位放在员工信息的属性数组中
            let userInfoMap = {}
            for (let i = 0; i != res.length; i++) {
                userInfoMap[res[i].uid] = userInfoMap[res[i].uid] || { departPoses: [] }
                userInfoMap[res[i].uid].id = res[i].id
                userInfoMap[res[i].uid].uid = res[i].uid
                userInfoMap[res[i].uid].name = res[i].name
                userInfoMap[res[i].uid].gender = res[i].gender
                userInfoMap[res[i].uid].leixing = res[i].leixing
                userInfoMap[res[i].uid].xingzhi = res[i].xingzhi
                userInfoMap[res[i].uid].zhiji = res[i].zhiji
                userInfoMap[res[i].uid].upper = res[i].upper
                userInfoMap[res[i].uid].phone = res[i].phone
                userInfoMap[res[i].uid].email = res[i].email
                userInfoMap[res[i].uid].sta = res[i].sta
                userInfoMap[res[i].uid].password = res[i].password
                userInfoMap[res[i].uid].createtime = moment(res[i].createtime).format('YYYY-MM-DD')
                userInfoMap[res[i].uid].departPoses.push({dpid: res[i].dpid, department: res[i].department, position: res[i].position, name: res[i].departmentName + '-' + res[i].positionName})
            }
            // 将员工信息对象展开成数组
            let userInfoAry = []
            for (let uid in userInfoMap) {
                userInfoAry.push(userInfoMap[uid])
            }
            userInfoAry.sort((a, b) => { return a.id - b.id })
            ctx.body = {code: 0, message: 'success', data: {list: userInfoAry, count}};
        }
        catch (err) {
            logger.error(err);
            ctx.body = {code: -1, message: 'system error'};
        }
    },

    // 添加员工
    addUser: async ctx => {
        let params = ctx.request.body
        logger.debug(params)
        if (!params.name || !params.password || !params.phone || !params.email || !params.sta || !params.departPoses) return ctx.body = {code: -1, message: '参数缺失1'}

        if (!Array.isArray(params.departPoses) || params.departPoses.length == 0) {
            return ctx.body = {code: -1, message: '参数错误'}
        }

        for (let i = 0; i != params.departPoses.length; i++) {
            if (!params.departPoses[i].department || !params.departPoses[i].position) {
                return ctx.body = {code: -1, message: '参数缺失2'}
            }
        }

        try {
            // 检查手机号码是否重复
            let res = await mysqlUtil.execute('SELECT 1 FROM tb_user WHERE phone = ? LIMIT 1', [params.phone])
            if (res.length != 0) return ctx.body = {code: -1, message: '手机号码已经被使用'}

            // 检查邮箱是否重复
            res = await mysqlUtil.execute('SELECT 1 FROM tb_user WHERE email = ? LIMIT 1', [params.email])
            if (res.length != 0) return ctx.body = {code: -1, message: '邮箱已被使用'}

            // 生成1个新的id
            let uid = await newUid()
            if (uid == 0) return ctx.body = {code: -1, message: '系统繁忙，请稍后再试'}

            // 添加新用户
            await mysqlUtil.execute('INSERT INTO tb_user SET ?', [{
                uid,
                name: params.name,
                password: params.password,
                avatar: 'defaultavatar.png',
                phone: params.phone,
                email: params.email,
                lastlogintime: 0,
                sta: params.sta,
                createtime: Date.now(),
                updatetime: Date.now()
            }])

            // 添加到用户部门表中
            let departPoses = []
            for (let i = 0; i != params.departPoses.length; i++) {
                departPoses.push([uid, params.departPoses[i].department, params.departPoses[i].position, Date.now()])
            }

            await mysqlUtil.execute('INSERT INTO tb_user_depart_pos(uid, department, position, createTime) VALUES ?', [departPoses])

            // 通知刷新架构
            redisUtil.client.publish('REFRESH_CONTACT', 'aaa')

            ctx.body = {code: 0, message: 'success'}
        } catch (err) {
            logger.error(err)
            ctx.body = {code: -1, message: 'system error'}
        }
    },

    // 修改员工密码
    modifyUserPwd: async ctx => {
        let params = ctx.request.body;
        if (!params.uid || !params.password) return ctx.body = {code: -1, message: '参数缺失'}

        try {
            let res = await mysqlUtil.execute('UPDATE tb_user SET password = ? WHERE uid = ? LIMIT 1', [params.password, params.uid])
            if (res.affectedRows == 0) return ctx.body = {code: -1, message: '员工不存在'}
            ctx.body = {code: 0, message: 'success'}
        } catch (err) {
            logger.error(err)
            ctx.body = {code: -1, message: 'system error'}
        }
    },

    // 删除员工
    delUser: async ctx => {
        let params = ctx.request.body
        if (!params.uid) return ctx.body = {code: -1, message: '参数缺失'}

        try {
            await mysqlUtil.execute('DELETE FROM tb_user_depart_pos WHERE uid = ?', [params.uid])
            await mysqlUtil.execute('DELETE FROM tb_user WHERE uid = ? LIMIT 1', [params.uid])

            // 通知刷新架构
            redisUtil.client.publish('REFRESH_CONTACT', 'aaa')

            ctx.body = {code: 0, message: 'success'}
        } catch (err) {
            logger.error(err)
            ctx.body = {code: -1, message: 'system error'}
        }
    },

    // 从岗位职位中删除
    rmFromDp: async ctx => {
        let params = ctx.request.body
        if (!params.dpid) return ctx.body = {code: -1, message: '参数缺失'}

        try {
            let sql = `SELECT COUNT(1) cnt FROM tb_user_depart_pos WHERE uid = (SELECT uid FROM tb_user_depart_pos WHERE id = ? LIMIT 1)`
            let res = await mysqlUtil.execute(sql, [params.dpid])
            if (res[0].cnt <= 1) return ctx.body = {code: -1, message: '不能删除唯一岗位'}
            res = await mysqlUtil.execute('DELETE FROM tb_user_depart_pos WHERE id = ? LIMIT 1', params.dpid)
            if (res.affectedRows == 0) return ctx.body = {code: -1, message: '岗位不存在'}

            ctx.body = {code: 0, message: 'success'}
        } catch (err) {
            logger.error(err)
            ctx.body = {code: -1, message: 'system error'}
        }
    },

    // 调整部门岗位
    updateUserDp: async ctx => {
        let params = ctx.request.body
        if (!params.uid || !params.dpid || !params.department || !params.position) {
            return ctx.body = {code: -1, message: '参数缺失'}
        }
        try {
            let sql = 'SELECT COUNT(1) cnt FROM tb_user_depart_pos WHERE id != ? AND uid = ? AND department = ?'
            let res = await mysqlUtil.execute(sql, [params.dpid, params.uid, params.department])
            if (res[0].cnt != 0) return ctx.body = {code: -1, message: '在一个部门中只能担任一个岗位'}
            sql = `UPDATE tb_user_depart_pos SET department = ?, position = ? WHERE id = ? LIMIT 1`
            await mysqlUtil.execute(sql, [params.department, params.position, params.dpid])
            ctx.body = {code: 0, message: 'success'}
        } catch (err) {
            logger.error(err)
            ctx.body = {code: -1, message: 'system error'}
        }
    },

    // 添加员工部门岗位
    addUserDp: async ctx => {
        let params = ctx.request.body
        if (!params.uid || !params.department || !params.position) return ctx.body = {code: -1, message: '参数缺失'}

        try {
            let res = await mysqlUtil.execute('SELECT 1 FROM tb_user_depart_pos WHERE uid = ? AND department = ? LIMIT 1', [params.uid, params.department])
            if (res.length != 0) return ctx.body = {code: -1, message: '在一个部门中只能担任一个岗位'}
            await mysqlUtil.execute('INSERT INTO tb_user_depart_pos SET ?', [{
                uid: params.uid,
                department: params.department,
                position: params.position,
                createTime: Date.now()
            }])
            ctx.body = {code: 0, message: 'success'}
        } catch (err) {
            logger.error(err)
            ctx.body = {code: -1, message: 'system error'}
        }
    },

    // 更新员工信息
    updateUserInfo: async ctx => {
        let params = ctx.request.body
        if (!params.uid) return ctx.body = {code: -1, message: '参数缺失'}
        if (!params.name && !params.phone && !params.email && !params.password && !params.sta) return ctx.body = {code: -1, message: '参数缺失'}
        try {
            let updateInfo = {}
            if (params.name) {
                updateInfo.name = params.name
            }
            if (params.phone) {
                updateInfo.phone = params.phone
            }
            if (params.email) {
                updateInfo.email = params.email
            }
            if (params.password) {
                updateInfo.password = params.password
            }
            if (params.sta) {
                updateInfo.sta = params.sta
            }
            await mysqlUtil.execute('UPDATE tb_user SET ? LIMIT 1', [updateInfo, params.uid])
            ctx.body = {code: 0, message: 'success'}
        } catch (err) {
            logger.error(err)
            ctx.body = {code: -1, message: 'system error'}
        }
    }
}
